<template>
  <!-- 设备批量导入对话框 -->
  <el-drawer
    :wrapperClosable="false"
    :title="title"
    :visible.sync="open"
    direction="rtl"
  >
    <el-container>
      <el-main>
        <el-form ref="form" :model="form" label-width="80px">

          <!-- 产品名称 -->
          <el-form-item label="所属产品" prop="productId">
            <el-select v-model="form.productId" placeholder="请选择所属产品" class="select-width">
              <el-option
                v-for="dict in productList"
                :key="dict.id"
                :label="dict.productName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <!--选择文件格式-->
          <el-form-item v-if="visible" label="文件格式" prop="fileType">
            <el-radio-group v-model="form.fileType">
              <el-radio-button label="xisx"></el-radio-button>
              <el-radio-button label="csv"></el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!--文件上传按钮-->
          <el-form-item v-if="visible" label="上传文件" prop="file">
            <files-upload :on-success="onSuccess" ref="filesUpload"/>
          </el-form-item>

          <!--文件模板下载按钮-->
          <el-form-item v-if="visible" label="下载模板">
            <el-button type="primary" @click="importXISX">下载xisx文件模板</el-button>
            <el-button type="primary" @click="importCSV">下载csv文件模板</el-button>
          </el-form-item>


        </el-form>
      </el-main>
      <el-footer>
        <div class="bottom-bar" style="text-align: right">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-footer>
    </el-container>
  </el-drawer>
</template>

<script>
  import FilesUpload from '@/views/iot/device/filesUpload'
  import {
    importAllDevice,
  } from '@/api/iot/device'
  import { listProduct } from '@/api/iot/product'
  import {mapState} from 'vuex'

  export default {
    name: "ImportAddEdit",
    components: {
      FilesUpload,
    },
    dicts: [],
    data() {
      return {
        //导出模板需要的空文件
        importNULL: null,
        //控制导入文件页面
        visible: false,
        //产品列表
        productList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          publishState: null,
        },
        // 表单参数
        form: {},
      }
    },
    computed: {
    },
    watch: {
      'form.productId'(type) {
        if (!type) {
          this.visible = false;
        } else {
          this.visibleByfile(type);
        }
      },
    },
    created() {
    },
    methods: {
      onSuccess(data) {
        this.postBatchUser(data.results)
      },
      async postBatchUser(userList) {
        // 对照表(中英文对照表)
        const zhToEnMap = {
          网关设备: 'gatewayDevice',
          所属产品: 'productId',
          所属分组: 'groupId',
          其他配置: 'configuration',
          设备名称: 'deviceName',
          设备编号: 'deviceCode',
          设备状态: 'deviceState',
          设备特性: 'features',
          设备描述: 'description',
          注册时间: 'registryTime',
          创建时间: 'createTime',
          更新时间: 'updateTime'
        };
        const postData = userList.map((item) => {
          const userInfo = {};
          Object.keys(item).forEach((zhKey) => {
            const enKey = zhToEnMap[zhKey];
            // 生成新的英文的 key 对应的 对象
            userInfo[enKey] = item[zhKey]
          });
          return userInfo
        });
        this.form.configuration.list = postData;
        this.$message.success('文件读取成功')
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          configuration: {},
          gatewayDevice: null,
          productId: null,
          groupId: null,
          deviceName: null,
          deviceCode: null,
          deviceState: null,
          features: null,
          registryTime: null,
          createTime: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.queryParams.publishState = 1;
        listProduct(this.queryParams).then(response => {
          this.productList = response.rows;
        });
        this.open = true;
        this.title = "导入设备";
      },
      /** 确定按钮 **/
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let form = JSON.parse(JSON.stringify(this.form));
            form.configuration.list = JSON.stringify(form.configuration.list);
            importAllDevice(form.configuration.list).then(() => {
              this.$modal.msgSuccess("批量导入成功");
              this.open = false;
            })
          }
        });
      },
      visibleByfile(type) {
        this.visible = true;
      },
      /** 导出按钮操作 */
      importXISX() {
        this.download('iot/device/export/null', {
          ...this.importNULL
        }, `xisx模板${new Date().getTime()}.xlsx`)
      },
      /** 导出按钮操作 */
      importCSV() {
        this.download('iot/device/export/null', {
          ...this.importNULL
        }, `csv模板${new Date().getTime()}.csv`)
      },
    }
  };
</script>

<style lang="scss" scoped>

</style>
